package com.tunghuynh.game.th_flappybird;

import java.util.ArrayList;
import java.util.List;

import com.tunghuynh.hpbd.Global;
import com.tunghuynh.hpbd.R;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class FlappyBird extends Activity implements OnTouchListener {
	private Paint paintPipe = new Paint();
	private Paint paintBird = new Paint();
	DrawPanel dp;
	private static TextView txtScore, txtMsg;
	private MediaPlayer mpHit, mpWing, mpPoint;

	int xBird = 250, yBird = 450, rBird = 25, jumpBird = 3;
	int[] aX = new int[5];
	int[] aY = new int[10];
	int iR = 0, index = 0, view = 2, startDraw = 0, jump = 2;
	int score = 0;
	boolean isDead = false;
	String[] template = Common._template();
	List<List<Coordinate>> q = new ArrayList<List<Coordinate>>();
	List<List<Coordinate>> qTemp = new ArrayList<List<Coordinate>>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_flappy_bird);
		txtScore = (TextView) findViewById(R.id.txtScore);
		txtMsg = (TextView) findViewById(R.id.txtMsg2);

		mpHit = MediaPlayer.create(FlappyBird.this, R.raw.hit);
		mpWing = MediaPlayer.create(FlappyBird.this, R.raw.wing);
		mpPoint = MediaPlayer.create(FlappyBird.this, R.raw.point);

		txtMsg.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isDead) {
					init();
				} else if (Global.game2IsPassed) {
					finish();
				}
			}
		});

		dp = new DrawPanel(this);
		dp.setOnTouchListener(this);

		paintPipe.setColor(Color.GREEN);
		paintPipe.setStrokeWidth(3);
		paintPipe.setTextSize(25);
		// paintPipe.setShader(new RadialGradient(10, 10, 100 / 3, Color.GREEN,
		// Color.YELLOW, Shader.TileMode.MIRROR));

		paintBird.setColor(Color.RED);
		paintBird.setTextSize(25);

		LinearLayout fl = (LinearLayout) findViewById(R.id.layoutCanvas2);
		fl.addView(dp);

		msbox("Tip",
				"Tap vào màn hình để di chuyển vật thể vuông màu Đỏ nhịp nhàng qua 22 cột màu.");
	}

	@Override
	protected void onPause() {
		super.onPause();
		dp.pause();
		// Global.stopSound();
	}

	@Override
	protected void onResume() {
		super.onResume();
		dp.resume();
	}

	public void msbox(String title, String msg) {
		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setTitle(title);
		dlgAlert.setMessage(msg);
		dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				init();
			}
		});
		dlgAlert.setCancelable(true);
		dlgAlert.create().show();
	}

	private void showMsg(final String text, final boolean state) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (state) {
					txtMsg.setVisibility(View.VISIBLE);
				} else {
					txtMsg.setVisibility(View.INVISIBLE);
				}
				txtMsg.setText(text);
			}
		});
	}

	private void init() {
		showMsg("", false);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				txtScore.setText("0");
			}
		});
		index = 0;
		isDead = false;
		Global.game2IsPassed = false;
		score = 0;
		jumpBird = 3;
		jump = 2;
		xBird = 250;
		yBird = 450;
		qTemp = new ArrayList<List<Coordinate>>();
		q = new ArrayList<List<Coordinate>>();
		for (int i = 0; i < template.length; i++) {
			List<Coordinate> c = new ArrayList<Coordinate>();
			for (int j = 0; j < template[i].length(); j++) {
				if (template[i].charAt(j) == '1') {
					c.add(new Coordinate(i, j));
				}
			}
			if (c.size() > 0) {
				qTemp.add(c);
			}
		}
	}

	public boolean onTouch(View v, MotionEvent me) {
		if (me.getAction() == MotionEvent.ACTION_DOWN) {
			jumpBird *= -1;
			mpWing.start();
		}
		return true;
	}

	@SuppressLint("WrongCall")
	public class DrawPanel extends SurfaceView implements Runnable {
		Thread t = null;
		SurfaceHolder holder;
		boolean isItOk = false;

		public DrawPanel(Context context) {
			super(context);
			holder = getHolder();
		}

		public void run() {
			while (isItOk == true) {
				if (!holder.getSurface().isValid()) {
					continue;
				}
				Canvas c = holder.lockCanvas();
				c.drawARGB(255, 255, 255, 255);
				onDraw(c);
				holder.unlockCanvasAndPost(c);
			}
		}

		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			if (iR == 0) {
				iR = canvas.getHeight() / 10;
				rBird = iR / 4;
			}
			// Bird
			if (isDead) {
				jump = 0;
				jumpBird = 0;
				showMsg("Play again", true);
			}
			if (Global.game2IsPassed) {
				jump = 0;
				jumpBird = 0;
				showMsg("You passed!", true);
			}
			if (yBird < rBird || yBird > canvas.getHeight() - rBird) {
				jumpBird *= -1;
			}
			yBird += jumpBird;
			canvas.drawRect(xBird - rBird, yBird - rBird, xBird + rBird, yBird
					+ rBird, paintBird);
			// Cột
			if (q.size() > 0) {
				if (q.get(0).size() > 0) {
					if (q.get(0).get(0).X + iR < 0) {
						q.remove(0);
					}
				}
			}
			if (q.size() < view) {
				int x = 500;
				List<Coordinate> c = new ArrayList<Coordinate>();
				if (q.size() > 0) {
					c = q.get(q.size() - 1);
					x = c.get(0).X;
				}
				if (index < qTemp.size()) {
					List<Coordinate> cTemp = new ArrayList<Coordinate>();
					for (Coordinate coor : qTemp.get(index)) {
						cTemp.add(new Coordinate((x + iR / 10 * 35), coor.Y
								* iR));
						System.out
								.println("Added " + index + ": ("
										+ (x + iR / 10 * 35) + ", " + coor.Y
										* iR + ")");
					}
					index++;
					q.add(cTemp);
					System.out.println("++ " + q.size());
				}
			}
			for (List<Coordinate> lst : q) {
				if (lst.get(0).X < 250 && lst.get(0).X >= 250 - jump) {
					score++;
					mpPoint.start();
					if (score >= qTemp.size()) {
						Global.game2IsPassed = true;
					}
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							txtScore.setText(score + "");
						}
					});
				}
				for (Coordinate coor : lst) {
					if (Math.abs(coor.X + iR / 2 - xBird) < (rBird + iR / 2)
							&& Math.abs(coor.Y + iR / 2 - yBird) < (rBird + iR / 2)) {
						if (!isDead) {
							mpHit.start();
						}
						isDead = true;

					}
					coor.X -= jump;
					canvas.drawRect(coor.X, coor.Y, coor.X + iR, coor.Y + iR,
							paintPipe);
				}
			}
		}

		public void pause() {
			isItOk = false;
			while (true) {
				try {
					t.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				break;
			}
			t = null;
		}

		public void resume() {
			isItOk = true;
			t = new Thread(this);
			t.start();
		}
	}
}
